<template>
  <div style="width: 100%">
    <el-select
      v-model="modelForm[config.prop]"
      v-bind="config.setting"
      :disabled="config.disabled && config.disabled(modelForm)"
      @change="config.onChange && config.onChange(modelForm)"
    >
      <el-option
        v-for="selectTtem in options"
        :key="selectTtem.value"
        :label="selectTtem.label"
        :value="selectTtem.value"
        :disabled="selectTtem.disabled"
      ></el-option>
    </el-select>
  </div>
</template>

<script setup>
import { onMounted, ref, watch, computed } from "vue";
import { mAxios } from "~/utils/axios/axios.js";
const modelForm = defineModel();
const props = defineProps({
  config: {
    type: Object,
    default: {},
  },
});
const emits = defineEmits(["resetFields"]);
const options = ref([]);
const getOptions = () => {
  if (remoteType.value == "custom_remote") {
    props.config.setting
      .remoteMethod(modelForm.value)
      .then((res) => {
        if (props.config.setting?.formatter) {
          let data = props.config.setting.formatter.data?res.data[props.config.setting.formatter.data]:res.data
          options.value = data.map(item => {
            return {
              label: item[props.config.setting.formatter.label],
              value: item[props.config.setting.formatter.value]
            }
          })
        } else {
          options.value = res;
        }
      })
      .catch(() => {
        emits("resetFields");
        options.value = [];
      });
  } else {
    options.value = props.config.options;
  }
};

const remoteType = computed(() => {
  // if (
  //   props.config.setting.remote &&
  //   props.config.setting.remoteParams &&
  //   props.config.setting.remoteMethod == "log_dict"
  // ) {
  //   return "log_dict";
  // }
  if (
    props.config.setting?.remote &&
    props.config.setting?.remoteMethod &&
    typeof props.config.setting?.remoteMethod == "function"
  ) {
    return "custom_remote";
  }
  return "";
});
onMounted(() => {
  getOptions();
  props.config.setting?.watchFields?.forEach((item) => {
    watch(
      () => modelForm.value[item],
      (value) => {
        // modelForm.value[props.config.prop] = "";
        getOptions();
      },
      {
        deep: true,
      }
    );
  });
});
</script>